import { createSite, type SiteParam, updateSite } from '@/api/SiteApi.ts'
import { type ArcoForm, type ArcoFormRules, ArcoFormTool } from '@/tool/ArcoFormTool.ts'
import { GeneralModelService } from '@/tool/GeneralModelService.ts'
import { ObjectTool } from '@es-tool/core'
import { type Ref, ref, watch } from 'vue'

export type PropsType = {
    groupId: string,
    isAdd?: boolean,
    site?: object
}

export type EmitsType = {
    (event: 'change'): void
}

export class SiteFormModal extends GeneralModelService {

    public readonly props: PropsType

    public readonly emits: EmitsType

    public readonly formRef: Ref<ArcoForm | null>

    public readonly formIsLoading: Ref<boolean> = ref(false)

    public readonly formData: Ref<Partial<SiteParam>> = ref<Partial<SiteParam>>(this.newDefaultSite())

    public readonly formRule: ArcoFormRules<SiteParam> = {
        name: [ { type: 'string', required: true, message: '', maxLength: 200 } ],
    }

    public constructor(props: PropsType, emits: EmitsType, formRef: Ref<ArcoForm | null>) {
        super()
        this.props = props
        this.emits = emits
        this.formRef = formRef

        watch(() => props.site, () => {
            if (this.props.site) {
                const site = ObjectTool.copy(this.props.site)
                this.formData.value = site ?? this.newDefaultSite()
            }
        }, { immediate: true })

        this.formSubmit = this.formSubmit.bind(this)
    }

    public async formSubmit(): Promise<boolean> {
        try {
            this.formData.value.groupId = this.props.groupId

            this.formIsLoading.value = true
            await ArcoFormTool.validate(this.formRef)

            await (this.props.isAdd
                    ? createSite(this.formData.value as any)
                    : updateSite(this.formData.value as any))
            if (this.props.isAdd) {
                this.formData.value = this.newDefaultSite()
            }
            this.emits('change')
            return true
        } catch (e) {
            console.debug(e)
            return false
        } finally {
            this.formIsLoading.value = false
        }
    }

    private newDefaultSite(): Partial<SiteParam> {
        return {
            url: '',
            icon: '',
            description: '',
            name: '',
            sort: 10000,
            groupId: '',
        }
    }

}
